package com.linkgie.galaxyframework.utils.bean;

import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.lang.Nullable;

import com.linkgie.galaxyframework.utils.StringConverter;

class ExtBeanWrapperImpl extends BeanWrapperImpl {

	ExtBeanWrapperImpl(Class<?> beanClass) {
		super(beanClass);
	}

	ExtBeanWrapperImpl(Object beanInstance) {
		super(beanInstance);
	}

	@Override
	@Nullable
	public PropertyEditor findCustomEditor(@Nullable Class<?> requiredType, @Nullable String propertyPath) {
		PropertyEditor editor = super.findCustomEditor(requiredType, propertyPath);
		if (editor == null) {
			Class<?> valueType;
			StringConverter<?> converter;
			// 自定义类型；
			if (propertyPath == null) {
				converter = BeanConverterRegistry.getBeanConverter(requiredType);
				valueType = requiredType;
			} else {
				try {
					PropertyDescriptor propertyDescriptor = getPropertyDescriptor(propertyPath);
					converter = BeanConverterRegistry.getPropertyConverter(propertyDescriptor);
					valueType = propertyDescriptor.getPropertyType();
				} catch (InvalidPropertyException e) {
					return null;
				}
			}
			if (converter == null) {
				return null;
			}
			return new BeanPropertyEditor(valueType, converter);
		}

		return editor;
	}
}